package org.xxpay.pay.channel.vip;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.xxpay.common.http.HttpRequestTemplate;
import org.xxpay.common.util.HtmlUtils;
import org.xxpay.common.util.Util;
import org.xxpay.common.util.sign.SignUtils;
import org.xxpay.core.common.constant.PayConstant;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.pay.channel.BasePayment;

import java.util.HashMap;
import java.util.Map;

/**
 * @Package org.xxpay.pay.channel.vip
 * @Class: VippayPaymentService.java
 * @Description:
 * @Author leo
 * @Date 2019/3/30 16:03
 * @Version
 **/
@Component
public class VippayPaymentService extends BasePayment {

    private final static String logPrefix = "【VIP】";

    // 下单
    private final static String ORDER_CREATE_STR = "/api/order";
    // 订单查询
    private final static String ORDER_QUERY_STR = "/api/query";

    @Override
    public String getChannelName() {
        return VippayConfig.CHANNEL_NAME;
    }

    @Override
    public JSONObject pay(PayOrder payOrder) {
        String channelId = payOrder.getChannelId();
        JSONObject retObj;
        switch (channelId) {
            case VippayConfig.CHANNEL_NAME_VIP_ALIQR:
                retObj = doOrderReq(payOrder);
                break;
            case VippayConfig.CHANNEL_NAME_QUICK_WAP:
                retObj = doOrderReq(payOrder);
                break;
            case VippayConfig.CHANNEL_NAME_B2C:
                retObj = doOrderReq(payOrder);
                break;
            case VippayConfig.CHANNEL_NAME_JD_QR:
                retObj = doOrderReq(payOrder);
                break;
            case VippayConfig.CHANNEL_NAME_UNION_QR:
                retObj = doOrderReq(payOrder);
                break;
            default:
                retObj = buildRetObj(PayConstant.RETURN_VALUE_FAIL, "不支持的渠道[channelId="+channelId+"]");
                break;
        }

        return retObj;
    }

    private JSONObject doOrderReq(PayOrder payOrder) {
        VippayConfig vippayConfig = new VippayConfig(getPayParam(payOrder));
        // 请求参数
        Map<String, Object> reqPrameters = Maps.newHashMap();
        reqPrameters.put("app_id", vippayConfig.getMchId());
        reqPrameters.put("order_sn", payOrder.getPayOrderId());
        reqPrameters.put("order_amount", Util.conversionYuanAmount(payOrder.getAmount()));
        reqPrameters.put("bank_code", vippayConfig.getPayMode());
        reqPrameters.put("notify_url", payConfig.getNotifyUrl(getChannelName()));
        reqPrameters.put("returnUrl", payOrder.getReturnUrl());

        String signTxt = SignUtils.parameterText(reqPrameters);
        _log.info("{}通道签名前字符串{}", logPrefix, signTxt);
        String sign = SignUtils.MD5.createSign(signTxt, "&"+vippayConfig.getPrivateKey(), SignUtils.CHARSET_UTF8);
        reqPrameters.put("signature", sign);
        _log.info("{}请求数据:{}", getChannelName(), JSON.toJSONString(reqPrameters));

        // 将订单改为支付中
        rpcCommonService.rpcPayOrderService.updateStatus4Ing(payOrder.getPayOrderId(), null);

        JSONObject retObj = new JSONObject();

        String payForm = HtmlUtils.form(getReqUrl(vippayConfig.getRequestUrl(),ORDER_CREATE_STR), HtmlUtils.POST, reqPrameters);

        retObj.put("payOrderId", payOrder.getPayOrderId());
        JSONObject payInfo = new JSONObject();
        payInfo.put("payUrl",payForm);
        payInfo.put("payMethod",PayConstant.PAY_METHOD_FORM_JUMP);
        retObj.put("payParams", payInfo);
        retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_SUCCESS);
        return retObj;
    }

    @Override
    public JSONObject query(PayOrder payOrder) {
        VippayConfig vippayConfig = new VippayConfig(getPayParam(payOrder));
        String payOrderId = payOrder.getPayOrderId();
        _log.info("{}开始查询盛付通通道订单,payOrderId={}", logPrefix, payOrderId);
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("app_id", vippayConfig.getAppId());
        parameters.put("order_sn", payOrder.getPayOrderId());

        String signTxt = SignUtils.parameterText(parameters);
        String sign = SignUtils.MD5.createSign(signTxt, "&"+vippayConfig.getPrivateKey(), SignUtils.CHARSET_UTF8);
        parameters.put("signature", sign);
        _log.info("{}请求参数：{}", logPrefix, parameters.toString());
        HttpRequestTemplate requestTemplate = new HttpRequestTemplate(null);

        JSONObject origin = requestTemplate.postForObject(getReqUrl(vippayConfig.getRequestUrl(), ORDER_QUERY_STR), parameters, JSONObject.class);
        _log.info("{}查单同步请求响应参数：{}", logPrefix, origin.toJSONString());
        // 响应对象
        JSONObject retObj = new JSONObject();
        if(StringUtils.equals(origin.getString("err"), VippayConfig.RETURN_VALUE_SUCCESS)) {
            JSONObject data = origin.getJSONObject("msg");
            // vip支付状态：1成功，2失败，4未支付
            String payStatus = data.getString("pay_status");
            // 已支付
            if(StringUtils.equals(VippayConfig.RETURN_VALUE_SUCCESS, payStatus)) {
                retObj.put("status", 2);
            } else {
                // 支付中
                retObj.put("status", 1);
            }
            retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_SUCCESS);
            retObj.put("channelOrderNo", origin.getString("orderid"));
            retObj.put("channelObj", origin);
            return retObj;
        }
        retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_FAIL);
        retObj.put(PayConstant.RESULT_PARAM_ERRDES, origin.getString("msg"));
        return retObj;
    }


}
